package com.yy.wga.user.service.utils;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.yy.wga.common.enmus.EResponseCode;
import com.yy.wga.common.exception.BusinessException;
import com.yy.wga.common.utils.common.StringUtils;
import com.yy.wga.common.utils.mapping.BeansUtils;
import com.yy.wga.common.utils.sign.Md5Utils;
import com.yy.wga.module.user.dto.WxGetPhoneNumberDTO;
import com.yy.wga.module.user.request.WxGetPhoneNumberRequest;
import com.yy.wga.module.user.request.WxGetUserInfoRequest;
import com.yy.wga.module.user.response.WxGetUserInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

/**
 * description
 *
 * @author <a href="mailto:ludezh@dingtalk.com"> ludezh </a>
 * @version 1.0.0   2020/6/6,15:15
 * @since 1.0.0     2020/6/6,15:15
 */
@Slf4j
public class WxCryptUtil {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 解密小程序用户手机号加密数据
     *
     * @param [request, sesionKey]
     * @return com.hrz.hrzb.entity.dto.WxGetPhoneNumberDTO
     * @author ludezh
     * @date 2020/6/6 16:12
     * @version 1.0.0
     */
    public static WxGetPhoneNumberDTO cryptXcxPhoneNum(WxGetPhoneNumberRequest request, String sesionKey) {
        JSONObject jsonObject = cryptXcxEncryptedData(request.getEncryptedData(), request.getIv(), sesionKey);
        if (null != jsonObject) {
            log.info("解密小程序用户手机号加密数据：" + jsonObject.toString());
            return BeansUtils.map(jsonObject, WxGetPhoneNumberDTO.class);
        }
        throw new BusinessException(EResponseCode.ILLEGAL_REQUEST);
    }

    /**
     * 解密小程序用户信息加密数据
     *
     * @param [request, sesionKey]
     * @return com.hrz.hrzb.entity.request.WxGetUserInfoRequest.UserInfo
     * @author ludezh
     * @date 2020/6/6 15:30
     * @version 1.0.0
     */
    public static WxGetUserInfoResponse cryptXcxUserInfo(WxGetUserInfoRequest request, String sesionKey) {
        JSONObject jsonObject = cryptXcxEncryptedData(request.getEncryptedData(), request.getIv(), sesionKey);
        if (null != jsonObject) {
            log.info("解密小程序用户信息加密数据结果：" + jsonObject.toString());
            return BeansUtils.map(jsonObject, WxGetUserInfoResponse.class);
        }
        throw new BusinessException(EResponseCode.ILLEGAL_REQUEST);
    }


    /**
     * 加密数据(encryptedData) 进行对称解密
     *
     * @param [encryptedData, iv, sessionKey]
     * @return com.alibaba.fastjson.JSONObject
     * @author ludezh
     * @date 2020/6/6 15:25
     * @version 1.0.0
     */
    public static JSONObject cryptXcxEncryptedData(String encryptedData, String iv, String sessionKey) {
        if (StringUtils.length(sessionKey) != 24) {
            return null;
        }
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
//            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, StandardCharsets.UTF_8);
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            log.error("加密数据进行对称解密发生异常", e);
        }
        return null;
    }

    /**
     * 微信支付退款异步通知加密数据解密
     * @param reqInfo
     * @param key
     * @return
     */
    public static String decryptReqInfo(String reqInfo, String key) {
        String result = null;
        try {
            // 对加密串A做base64解码，得到加密串B
            byte[] bt = Base64.decode(reqInfo);
            // 对商户key做md5，得到32位小写key* ( key设置路径：微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置 )
            String md5key = Md5Utils.getMd5(key).toLowerCase();
            // 用key*对加密串B做AES-256-ECB解密（PKCS7Padding）
            SecretKey secretKey = new SecretKeySpec(md5key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] resultbt = cipher.doFinal(bt);
            result = new String(resultbt);
        } catch (Exception e) {
            log.error("加密数据进行解密发生异常", e);
        }
        return result;
    }
}
